/**
 * 计数器类
 * @param {Number} options.value 初始值
 * @param {String} options.input 输入框
 * @param {String} options.plus +按钮
 * @param {String} options.minus -按钮
 */

function NumberInput (options) {
  var defaultOptions = {
    value: 1,
    max: 9999,
    min: 1,
    input: '#J_countInput',
    plus: '#J_countPlus',
    minus: '#J_countMinus'
  };
  options = $.extend({}, defaultOptions, options);
	  
  this.max = options.max;
  this.min = options.min;
  this.value = options.value;
  this.inputEl = $(options.input);
  this.plusEl = $(options.plus);
  this.minusEl = $(options.minus);
  this.init();
}

NumberInput.prototype.init = function() {
  this.listen();
  this.render();
}

NumberInput.prototype.plus = function () {
  if (this.value >= this.max) {
    return;
  }
  this.value++;
  this.render();
}

NumberInput.prototype.minus = function () {
  if (this.value <= this.min) {
    return;
  }
  this.value--;
  this.render();
}

NumberInput.prototype.render = function () {
  this.inputEl.val(this.value)
}

NumberInput.prototype.change = function () {
  var currentVal = parseInt(this.inputEl.val());
  if (isNaN(currentVal)) {
    return this.render();
  }
  if (currentVal >= this.min && currentVal <= this.max) {
    this.value = currentVal;
  }
  this.render();
}

NumberInput.prototype.listen = function () {
  this.plusEl.on('click', this.plus.bind(this));
  this.minusEl.on('click', this.minus.bind(this));
  this.inputEl.on('change', this.change.bind(this));
}
